package flib;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

import processing.core.PApplet;
import processing.core.PImage;
import processing.data.XML;
import simpleGui.GuiCheckButton;
import simpleGui.GuiCheckboxGroup;


 

public class FlibXSLX extends PApplet {
	XML xmlExcel;
	
	
	
	
	TreeMap<String,FlibBuilding>buildings=new TreeMap<String,FlibBuilding>();
	String path = "/Users/administrator/projekte/Doktor/References/PDF/Das Grundrisswerk scan/data/";
	String pathImageFolder = path + "img/";
	//String pathImageFolder = "/Users/administrator/Desktop/floorplans Final/floorplanImagesRIGHTSCLAE/";
	String pathOBJFolder = path + "obj/";
	String pathConfig = "/Users/administrator/Documents/workspace/FrameWork1308P2/flibConfig.xml";
	String pathSVGFolder = "/Users/administrator/Desktop/floorplans Final/svg/";
	String worksheet="exportBuilding.csv";
	String worksheetSVG="sheet1";
	String pathXSLX="/Users/administrator/desktop/grundrisswerkMetaDataDetailled.xlsx";
	
	
	public void setup() {
		setupBuildingsSVG(pathSVGFolder);
		setupBuildingsOBJ();
		readXLSXFile(worksheet);
		createPDF("/Users/administrator/Desktop/testTable01.pdf");
	}
	
	
	public void readXML(String filename){
		xmlExcel= loadXML(filename);
		  XML[] rows = xmlExcel.getChildren("Worksheet/Table/Row");
		  for (int i=1;i<rows.length;i++){
			  XML[] cells=rows[i].getChildren("Cell/Data");
			  for (int ii=0;ii<cells.length;ii++){
				
				  XML data=cells[ii];
				  String text=data.getContent();
				  if (ii==0&&text!=null){
					 
				  }
				
				
				
				  //byte[] ptext = String.getBytes("UTF-8");
				 
			  }
		  }
	}
	public  void readXLSXFile(String worksheet) 
	{
		//InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
		File excel =  new File ("/Users/administrator/desktop/grundrisswerkMetaDataDetailled.xlsx");
	    FileInputStream fis;
		try {
			fis = new FileInputStream(excel);
			
	        XSSFWorkbook wb = new XSSFWorkbook(fis);
	       
	       // XSSFWorkbookSettings workbookSettings = new XSSFWorkbookSettings();
	       // workbookSettings.setEncoding( "Cp1252" );
	        XSSFSheet ws = wb.getSheet(worksheet);
	
	        int rowNum = ws.getLastRowNum() + 1;
	        int colNum = ws.getRow(0).getLastCellNum();
	        String [][] data = new String [rowNum] [colNum];
	        XSSFRow rowHeader = ws.getRow(0);
	        HashMap<Integer,String>headerMap=new HashMap<Integer,String>();
	       
	        for (int j = 0; j < colNum; j++){
	        	XSSFCell cell = rowHeader.getCell(j);
	        	println("header:" +cell.toString());
	        	headerMap.put(j,cell.toString());
	        }
	        for(int i = 1; i <rowNum; i++){
	            XSSFRow row = ws.getRow(i);
	            if (row!=null){
	            FlibBuilding building=null;
	                for (int j = 0; j < colNum; j++){
	                    XSSFCell cell = row.getCell(j);
	                    if (cell!=null){
	                    	String text = cell.toString();
							if (j == 0) {
								if (text != null) {
									println("buildingName: " + text);
									building = buildings.get(text);

								}
							}

							if (text != null) {
								if (building != null) {
									building.metaData.put(headerMap.get(j),
											text);
								}
							}

	                    }
	                }
	            }
	                //println(building.metaData);
	        }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void setupBuildingsSVG(String folder){
		FloorplanLoader2D loader=new FloorplanLoader2D(new File(pathConfig));
		buildings=loader.loadBuildingsFromSVG(folder);
		
		println(buildings.size());
		//buildings=loadBuildings(pathOBJFolder);
	}
	public void setupBuildingsOBJ(){
		FloorplanLoader2D loader=new FloorplanLoader2D(new File(pathConfig));
		buildings=loader.loadBuildingsFromOBJ(pathOBJFolder);
		//buildings=loadBuildings(pathOBJFolder);
	}

	public void createPDF(String filename) {

		Vector<FlibBuilding> buildingList = new Vector<FlibBuilding>();
		for (Map.Entry<String, FlibBuilding> entry : buildings.entrySet()) {
			String key = entry.getKey();
			FlibBuilding value = entry.getValue();
			buildingList.add(value);
		}
		// step 1
		Document document = new Document();
		document.setMargins(40, 40, 20, 20);
		Font fontbold = FontFactory.getFont("Helvetica Neue", 6, Font.BOLD);
		Font fontNormal = FontFactory.getFont("Helvetica Neue", 6, Font.NORMAL);
		// step 2
		try {
			PdfWriter.getInstance(document, new FileOutputStream(filename));
			// step 3
			document.open();
			// step 4
			PdfPTable table = new PdfPTable(3);
			table.setWidthPercentage(100);
			table.setWidths(new int[] { 1, 1, 1 });
			for (int i = 0; i < buildingList.size() - 2; i++) {
				FlibBuilding building = buildingList.get(i);
				if (building.metaData.size() > 0) {
					PdfPCell cellImage = new PdfPCell();
					for (int ii = 0; ii < building.levels.size(); ii++) {
						FlibLevel level = building.levels.get(ii);
						String imgName = level.filename.replace("obj", "png");
						//imgName = imgName.replace("svg", "jpg");
						println("level.fileName: " + level.filename);
						// PImage img=this.loadImage(pathImageFolder+imgName);
						Image im;
						try {
							String path = pathImageFolder + imgName;
							File f = new File(path);
							if (f.exists()) {
								im = Image.getInstance(String.format(
										pathImageFolder + imgName, "0120903"));
								im.scalePercent(2f);
								cellImage.addElement(im);
								cellImage.setHorizontalAlignment(Element.ALIGN_CENTER);
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							println(e);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							println(e);
						}
						// img.filter(INVERT);

					}
					cellImage.setBorder(Rectangle.TOP);
					cellImage.setPaddingTop(5);
					table.addCell(cellImage);
					String description = building.metaData.get("Description");
					if (description == null) {
						PdfPCell cellEmpty = new PdfPCell();
						cellEmpty.setBorder(Rectangle.TOP);
						table.addCell(cellEmpty);
					}
					
					
					PdfPCell cellMeta = new PdfPCell();
					// Section section=new Section("test");

					String[] keys = new String[] { "Project", "Architect",
							"Published", "Filename" };
					for (int j = 0; j < keys.length; j++) {
						String value = building.metaData.get(keys[j]);
						Phrase meta = new Phrase();
						if (value != null) {
							meta.add(new Phrase(keys[j] + ": ", fontbold));
							cellMeta.addElement(new Phrase(keys[j], fontbold));
							meta.add(new Phrase(value.replace("\n", ""),
									fontNormal));
							cellMeta.addElement(new Phrase(value.replace("\n",
									""), fontNormal));
						}
						// cell.addElement(meta);
					}
					cellMeta.setBorder(Rectangle.TOP);
					// cellMeta.setVerticalAlignment(Element.ALIGN_CENTER);
					cellMeta.setPaddingBottom(10);
					table.addCell(cellMeta);
					PdfPCell cellDescription = new PdfPCell();

					
					if (description != null) {
						description = description.replace("\n", "");
						cellDescription.addElement(new Phrase("Description",
								fontbold));
						cellDescription.addElement(new Paragraph(description,
								fontNormal));
						cellDescription.setNoWrap(false);
						// value=value.replace("\n", "");
						cellDescription.setBorder(Rectangle.TOP);
						cellDescription.setPaddingBottom(10);
						// cellDescription.setVerticalAlignment(Element.ALIGN_CENTER);
						table.addCell(cellDescription);
					}
					
				}
				// Paragraph pg=;

			}
			document.add(table);

			// step 5
			document.close();
			println("pdf created");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			println(e);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			println(e);
		}

	}
	public void createPDF2(String filename) {

		Vector<FlibBuilding> buildingList = new Vector<FlibBuilding>();
		for (Map.Entry<String, FlibBuilding> entry : buildings.entrySet()) {
			String key = entry.getKey();
			FlibBuilding value = entry.getValue();
			buildingList.add(value);
		}
		// step 1
		Document document = new Document();
		document.setMargins(40, 40, 20, 20);
		Font fontbold = FontFactory.getFont("Helvetica Neue", 6, Font.BOLD);
		Font fontNormal = FontFactory.getFont("Helvetica Neue", 6, Font.NORMAL);
		// step 2
		try {
			PdfWriter.getInstance(document, new FileOutputStream(filename));
			// step 3
			document.open();
			// step 4
			PdfPTable table = new PdfPTable(3);
			table.setWidthPercentage(100);
			table.setWidths(new int[] { 1, 1, 1 });
			for (int i = 0; i < buildingList.size() - 2; i++) {
				FlibBuilding building = buildingList.get(i);
				if (building.metaData.size() > 0) {
					PdfPCell cellImage = new PdfPCell();
					for (int ii = 0; ii < building.levels.size(); ii++) {
						FlibLevel level = building.levels.get(ii);
						String imgName = level.filename.replace("obj", "png");
						//imgName = imgName.replace("svg", "jpg");
						println("level.fileName: " + level.filename);
						// PImage img=this.loadImage(pathImageFolder+imgName);
						Image im;
						try {
							String path = pathImageFolder + imgName;
							File f = new File(path);
							if (f.exists()) {
								im = Image.getInstance(String.format(
										pathImageFolder + imgName, "0120903"));
								im.scalePercent(2f);
								cellImage.addElement(im);
								cellImage.setHorizontalAlignment(Element.ALIGN_CENTER);
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							println(e);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							println(e);
						}
						// img.filter(INVERT);

					}
					cellImage.setBorder(Rectangle.TOP);
					cellImage.setPaddingTop(5);
					table.addCell(cellImage);
					String description = building.metaData.get("Description");
					if (description == null) {
						PdfPCell cellEmpty = new PdfPCell();
						cellEmpty.setBorder(Rectangle.TOP);
						table.addCell(cellEmpty);
					}
					
					
					PdfPCell cellMeta = new PdfPCell();
					// Section section=new Section("test");

					String[] keys = new String[] { "Project", "Architect",
							"Published", "Filename" };
					for (int j = 0; j < keys.length; j++) {
						String value = building.metaData.get(keys[j]);
						Phrase meta = new Phrase();
						if (value != null) {
							meta.add(new Phrase(keys[j] + ": ", fontbold));
							cellMeta.addElement(new Phrase(keys[j], fontbold));
							meta.add(new Phrase(value.replace("\n", ""),
									fontNormal));
							cellMeta.addElement(new Phrase(value.replace("\n",
									""), fontNormal));
						}
						// cell.addElement(meta);
					}
					cellMeta.setBorder(Rectangle.TOP);
					// cellMeta.setVerticalAlignment(Element.ALIGN_CENTER);
					cellMeta.setPaddingBottom(10);
					table.addCell(cellMeta);
					PdfPCell cellDescription = new PdfPCell();

					
					if (description != null) {
						description = description.replace("\n", "");
						cellDescription.addElement(new Phrase("Description",
								fontbold));
						cellDescription.addElement(new Paragraph(description,
								fontNormal));
						cellDescription.setNoWrap(false);
						// value=value.replace("\n", "");
						cellDescription.setBorder(Rectangle.TOP);
						cellDescription.setPaddingBottom(10);
						// cellDescription.setVerticalAlignment(Element.ALIGN_CENTER);
						table.addCell(cellDescription);
					}
					
				}
				// Paragraph pg=;

			}
			document.add(table);

			// step 5
			document.close();
			println("pdf created");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			println(e);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			println(e);
		}

	}
	
}
